﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Football;
using System.Xml;

class FootballManagement
{
    public static void AddGame(int homeTeam, int awayTeam)
    {
        DataClassesFootballDataContext context = new DataClassesFootballDataContext();
        using (context)
        {
            Game newGame = new Game()
            {
                AwayId = awayTeam,
                AwayScore = 1,
                Date = DateTime.Now,
                HomeId = homeTeam,
                HomeScore = 3
            };
            context.Games.InsertOnSubmit(newGame);
            context.SubmitChanges();
        }
    }

    public static int AddTeam()
    {
        while (true)
        {
            Console.Write("Enter team name:");
            string name = Console.ReadLine();
            Console.Write("Enter owner:");
            string owner = Console.ReadLine();
            Console.Write("Enter team's town:");
            string town = Console.ReadLine();
            Console.Write("Enter team's stadium:");
            string stadium = Console.ReadLine();
            Console.Write("Enter stadium capacity:");
            int capacity = int.Parse(Console.ReadLine());
            Team newTeam = new Team()
            {
                Capacity = capacity,
                Owner = owner,
                StadiumName = stadium,
                TeamName = name,
                Town = town
            };

            DataClassesFootballDataContext context = new DataClassesFootballDataContext();
            using (context)
            {
                bool teamRepeats = false;
                foreach (Team team in context.Teams)
                {
                    if (newTeam.TeamName == team.TeamName)
                    {
                        Console.WriteLine("Team already exists enter another!");
                        teamRepeats = true;
                        break;
                    }
                }
                if (teamRepeats)
                {
                    continue;
                }

                context.Teams.InsertOnSubmit(newTeam);
                context.SubmitChanges();
                return newTeam.TeamId;
            }
        }
    }

    public static void AddTwoTeamsAndGame()
    {
        Console.WriteLine("Enter home team:");
        int homeTeam = AddTeam();
        Console.WriteLine("Enter away team:");
        int awayTeam = AddTeam();
        AddGame(homeTeam, awayTeam);
    }

    public static void ScoreBoard(XmlTextWriter writer)
    {
        DataClassesFootballDataContext context = new DataClassesFootballDataContext();
        using (context)
        {
            List<Scoreboard> board = new List<Scoreboard>();
            foreach (Team item in context.Teams)
            {                
                int wins = (
                    from game in context.Games
                    where game.HomeId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore > game.AwayScore select team.TeamId).First()) ||
                          game.AwayId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore < game.AwayScore select team.TeamId).First())
                    select game).Count();

                int draws = (
                    from game in context.Games
                    where game.HomeId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore == game.AwayScore select team.TeamId).First()) ||
                          game.AwayId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore == game.AwayScore select team.TeamId).First())
                    select game).Count();

                int losses = (
                    from game in context.Games
                    where game.HomeId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore < game.AwayScore select team.TeamId).First()) ||
                          game.AwayId == ((from team in context.Teams where team.TeamName == item.TeamName && game.HomeScore > game.AwayScore select team.TeamId).First())
                    select game).Count();

                var goalsF1 = (from game in context.Games
                         where game.HomeId == (from team in context.Teams where team.TeamName == item.TeamName select team.TeamId).FirstOrDefault()
                         select game.HomeScore);
                var goalsF2 = (from game in context.Games
                         where game.AwayId == (from team in context.Teams where team.TeamName == item.TeamName select team.TeamId).FirstOrDefault()
                         select game.AwayScore);

                int goalsF = 0;
                if (goalsF1.Count() > 0)
                {
                    goalsF += goalsF1.Sum();
                }
                if (goalsF2.Count() > 0)
                {
                    goalsF += goalsF2.Sum();
                }

                
                var goalsA1 = (from game in context.Games
                     where game.HomeId == (from team in context.Teams where team.TeamName == item.TeamName select team.TeamId).First()
                     select game.AwayScore);
                var goalsA2 = (from game in context.Games
                     where game.AwayId == (from team in context.Teams where team.TeamName == item.TeamName select team.TeamId).First()
                     select game.HomeScore);
                
                int goalsA = 0;
                if (goalsA1.Count() > 0) 
                {
                    goalsA += goalsA1.Sum(); 
                }
                if (goalsA2.Count() > 0)
                {
                    goalsA += goalsA2.Sum();
                }

                Scoreboard row = new Scoreboard() 
                {
                    Team = item.TeamName,
                    Plays = wins + draws + losses,
                    Wins = wins,
                    Draws = draws,
                    Losses = losses,
                    GoalsF = goalsF,
                    GoalsA = goalsA,
                    GoalDiff = goalsF - goalsA,
                    Points = wins * 3 + draws
                };
                board.Add(row);
                TeamAchievments(row.Team, row.Wins, row.Draws, row.Losses, row.GoalsF, row.GoalsA, writer);
            }
            var newBoard = board.OrderByDescending(row => row.Points).ThenByDescending(row => row.GoalDiff).ThenBy(row => row.Team);
            int number = 1;
            Console.WriteLine("  |Team       | P| W| D| L| F| A| GD|Pts|");
            Console.WriteLine("----------------------------------------");
            foreach (var item in newBoard)
            {
                Console.WriteLine("{0,2}|{1,-11}|{2,2}|{3,2}|{4,2}|{5,2}|{6,2}|{7,2}|{8,3}|{9,3}|", number, item.Team, item.Plays, item.Wins, item.Draws, item.Losses, item.GoalsF,
                    item.GoalsA, item.GoalDiff, item.Points);
                number++;
            }
            Console.WriteLine();
        }
    }

    public static void AddSquad(string fileName)
    {
        DataClassesFootballDataContext context = new DataClassesFootballDataContext();
        using (context)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileName);
            XmlNode root = xmlDoc.DocumentElement;
            //foreach for games!
            foreach (XmlNode gameNode in root.ChildNodes)
            {
                int gameId = int.Parse(gameNode.Attributes["id"].Value);
                
                int homeTeamId =
                    (from game in context.Games
                     where game.GameId == gameId
                     select game.HomeId).First();

                int awayTeamId =
                    (from game in context.Games
                     where game.GameId == gameId
                     select game.AwayId).First();

                XmlNodeList teams = gameNode.ChildNodes;

                //home team
                foreach (XmlNode playerNode in teams[0])
                {
                    Player newPlayer = new Player()
                    {
                        Name = playerNode.Attributes["name"].Value,
                        Number = int.Parse(playerNode.Attributes["number"].Value),
                        TeamId = homeTeamId,
                    };
                    context.Players.InsertOnSubmit(newPlayer);
                    context.SubmitChanges();

                    PlayersForGame newPlayerForGame = new PlayersForGame() 
                    {
                        GameId = gameId,
                        PlayerId = newPlayer.PlayerId
                    };

                    context.PlayersForGames.InsertOnSubmit(newPlayerForGame);
                    context.SubmitChanges();
                }

                //away team
                foreach (XmlNode playerNode in teams[1])
                {
                    Player newPlayer = new Player()
                    {

                        Name = playerNode.Attributes["name"].Value,
                        Number = int.Parse(playerNode.Attributes["number"].Value),
                        TeamId = awayTeamId,
                    };
                    context.Players.InsertOnSubmit(newPlayer);
                    context.SubmitChanges();

                    PlayersForGame newPlayerForGame = new PlayersForGame()
                    {
                        GameId = gameId,
                        PlayerId = newPlayer.PlayerId
                    };
                    context.PlayersForGames.InsertOnSubmit(newPlayerForGame);
                    context.SubmitChanges();
                }                               
            }
        }
    }

    public static void Achievments(string fileName)
    {
        using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.IndentChar = '\t';
            writer.Indentation = 1;

            writer.WriteStartDocument();
            writer.WriteStartElement("teams");
            ScoreBoard(writer);
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }

    public static void TeamAchievments(string teamName, int wins, int draws, int losses, int goalsF, int goalsA, XmlTextWriter writer)

    {
        writer.WriteStartElement("team");
        writer.WriteAttributeString("name", teamName);

        writer.WriteStartElement("wins");
        writer.WriteValue(wins);
        writer.WriteEndElement();

        writer.WriteStartElement("draws");
        writer.WriteValue(draws);
        writer.WriteEndElement();

        writer.WriteStartElement("losses");
        writer.WriteValue(losses);
        writer.WriteEndElement();

        writer.WriteStartElement("goals-active");
        writer.WriteValue(goalsF);
        writer.WriteEndElement();

        writer.WriteStartElement("goals-passive");
        writer.WriteValue(goalsA);
        writer.WriteEndElement();

        writer.WriteEndElement();
    }
    static void Main()
    {
        //AddTwoTeamsAndGame();
        //AddGame(17, 16);
        //ScoreBoard();
        //AddSquad("../../Teams.xml");
        //Achievments("../../TeamsAchievements.xml");
    }
}

